package com.lagou.builder;

import com.lagou.config.Configuration;
import com.lagou.io.Resource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * 核心配置文件sqlMapConfig.xml解析类
 * @author shenguotao
 */
public class XmlConfigBuilder {
    public Configuration parseConfig(InputStream in) throws Exception {
        //1.解析SqlMapConfig.xml的内容
        Document document = new SAXReader().read(in).getDocument();
        Element rootElement = document.getRootElement();
        //查找所有的Properties元素
        List<Element> elementList = rootElement.selectNodes("//properties");
        Properties properties = new Properties();
        String name = null;
        String value = null;
        for(Element element : elementList) {
            name = element.attributeValue("name");
            value = element.attributeValue("value");
            properties.setProperty(name,value);
        }

        //2.设置数据库连接池
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(properties.getProperty("driverClass"));
        dataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        dataSource.setUser(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));

        Configuration configuration = new Configuration();
        configuration.setDataSource(dataSource);

        //3.解析mapper.xml,封装sql映射信息到MapperStatement
        List<Element> mapperElements = rootElement.selectNodes("//mapper");
        for(Element element : mapperElements) {
            String path = element.attributeValue("resource");
            InputStream mapperIn = Resource.getResourceAsSteam(path);
            XmlMapperBuilder mapperParser = new XmlMapperBuilder(configuration);
            mapperParser.parseMapper(mapperIn);
        }

        return configuration;
    }
}
